package person.bing.fbcloud.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import person.bing.fbcloud.entity.SysRouteDetail;
import person.bing.fbcloud.service.SysRouteDetailService;

import java.net.URI;
import java.util.List;

/**
 * @author: mengfanbing
 * @date: 2020/9/4 10:50
 */
@Slf4j
@Component
public class SysRouteLoadListener {
    public static final String GATEWAY_ROUTES = "geteway:geteway_routes";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysRouteDetailService sysRouteDetailService;

    @Async
    @EventListener(WebServerInitializedEvent.class)
    public void load(){
        redisTemplate.delete(GATEWAY_ROUTES);
        routeMessageToRedis();
    }

    //    把数据库中的配置放到redis中
    private void routeMessageToRedis(){
        List<SysRouteDetail> sysRouteDetailList = sysRouteDetailService.list();
        System.out.println("======添加route信息到redis start========");
        sysRouteDetailList.stream().forEach(sysRouteDetail -> {
            RouteDefinition routeDefinition = new RouteDefinition();
            BeanUtil.copyProperties(sysRouteDetail,routeDefinition);
            List<PredicateDefinition> predicateDefinitions = JSONUtil.toList(new JSONArray(sysRouteDetail.getPredicates()), PredicateDefinition.class);
            List<FilterDefinition> filterDefinitions = JSONUtil.toList(new JSONArray(sysRouteDetail.getFilters()), FilterDefinition.class);
            routeDefinition.setPredicates(predicateDefinitions);
            routeDefinition.setFilters(filterDefinitions);
            routeDefinition.setId(sysRouteDetail.getRouteId());
            routeDefinition.setUri(URI.create(sysRouteDetail.getUri()));
            log.info("加载路由:{},{}",sysRouteDetail.getRouteName(),sysRouteDetail);
            redisTemplate.opsForHash().put(GATEWAY_ROUTES,sysRouteDetail.getRouteId(), new JSONObject(routeDefinition).toString());
        });
        System.out.println("======end========");
    }
}
